package controller;


import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;


public class MailHandler {

    String to;
    String from;
    String host;
    Properties properties;
    Session session;
    MimeMessage msg;

    public int oneToOne(String receiver, String sender, String subject, String text) 
    {
        //method to send an email from one sender to one user 
        //params : receiver email , sender email , the subject of the email and the body of the email (all strings ) 
        //returns 1 if sending succeeds and 0 if sending fails 

        to = receiver;
        from = sender;
        host = "localhost";
        properties = System.getProperties();
        session = Session.getDefaultInstance(properties);
        try {

            msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(sender));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
            msg.setSubject(subject);
            msg.setText(text);
            Transport.send(msg);
            return 1;
        } catch (MessagingException ex) {
            System.out.println("Something Went wrong in Sending mail 1 to 1");
            //ex.printStackTrace();
            return 0;

        }

    }

    public int oneToMany(String sender, String[] receiver, String subject, String text) throws AddressException
    {
        //method to send email from one user to many receivers 
        //params : sender email , array of strings of receivers emails , subject of email and body of email (all strings)
        //returns 1 if sending succeeds and 0 if sending fails 
        
        from = sender;
        host = "localhost";
        properties = System.getProperties();
        session = Session.getDefaultInstance(properties);

        InternetAddress[] adresses = new InternetAddress[receiver.length];
        for (int i = 0; i < receiver.length; i++) {
            adresses[i] = new InternetAddress(receiver[i]);

        }
        try {

            msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(sender));
            msg.setRecipients(Message.RecipientType.TO, adresses);
            msg.setSubject(subject);
            msg.setText(text);
            Transport.send(msg);

            return 1;
        } catch (Exception ex) {
            System.out.println("Something Went wrong in Many Mails");
            //ex.printStackTrace();
            return 0;

        }

    }
}
